#!/bin/sh

. "${PM_FUNCTIONS}"

do_add_quirks()
{
	local quirks="$(lshal | \
		awk -F '[. ]' \
		'/  power_management.quirk.[0-9a-z_]+ = true/ \
			{gsub(/_/, "-", $5); printf("--quirk-%s ", $5)}')"
	echo "Adding quirks from HAL: $quirks"
	add_parameters $quirks
}

do_save_quirks()
{
	# better to gather too much information than not enough
	hgp="hal-get-property --udi /org/freedesktop/Hal/devices/computer --key"
	vendor=$($hgp system.hardware.vendor)
	product=$($hgp system.hardware.product)
	firmware=$($hgp system.firmware.version)
	video_vendor=$($hgp system.hardware.primary_video.vendor --hex)
	video_card=$($hgp system.hardware.primary_video.product --hex)
	(
	exec >"/etc/hal/fdi/information/99local-pm-utils-quirks.fdi"
	echo '<?xml version="1.0" encoding="ISO-8859-1"?> <!-- -*- SGML -*- -->'
	echo '<!-- Created by pm-utils -->'
	echo '<deviceinfo version="0.2">'
	echo '  <device>'
	echo "    <match key=\"system.hardware.vendor\" string=\"${vendor}\">"
	echo "      <match key=\"system.hardware.product\" string=\"${product}\">"
	echo "        <match key=\"system.firmware.version\" string=\"${firmware}\">"
	echo "          <match key=\"system.hardware.primary_video.vendor\" int=\"0x${video_vendor}\">"
	echo "            <match key=\"system.hardware.primary_video.product\" int=\"0x${video_card}\">"
	for p in ${PM_CMDLINE}; do
		quirk="${p#--quirk-}"
		[ "$p" = "$quirk" ] && continue
		echo "              <merge key=\"power_management.quirk.${quirk}\" type=\"bool\">true</merge>" |tr - _
	done
	echo "            </match>"
	echo "          </match>"
	echo "        </match>"
	echo "      </match>"
	echo "    </match>"
	echo "  </device>"
	echo "</deviceinfo>"
	)
	echo "FDI file created as /etc/hal/fdi/information/99local-pm-utils-quirks.fdi"
}
	
maybe_add_quirks()
{
	[ -z "$PM_CMDLINE" ] && {
		command_exists lshal || return $NA
		do_add_quirks
		return 0
	}
	command_exists lshal || { 
		echo "--auto-quirks requires HAL. Aborting"
		return 1
	}
	has_parameter --auto-quirks || return 0
	do_add_quirks
	remove_parameters --auto-quirks
}

maybe_save_quirks()
{
	inhibited && return 0
	has_parameter --store-quirks-as-fdi && do_save_quirks
	return 0
}

help()
{
	echo
	echo "Auto quirk handler option:"
	echo
	echo "  --auto-quirks"
	echo "  Running without any options will also invoke auto quirk."
	echo
	echo "  --store-quirks-as-fdi"
}

case $1 in
	suspend|hibernate) maybe_add_quirks ;;
	thaw|resume) maybe_save_quirks ;;
	help) help ;;
	*) exit $NA ;;
esac

